package controller;

import DAO.BaseDAO;
import DAO.MetricAdminDAO;
import DAO.UserDAO;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.servlet.http.HttpSession;
import model.Metric;
import model.User;
import org.apache.commons.mail.EmailException;

@ManagedBean(name = "userController")
@SessionScoped
public class UserController {

    private User user;
    public DataModel listUsers;

    public UserController() {
        user = new User();
    }

    public void saveUser() throws Exception {
        BaseDAO dao = new UserDAO();
        user.setRole(2);
        dao.save(user);
        setUser(new User());
    }

    public String updateUser() {
        BaseDAO dao = new UserDAO();
        dao.update(user);
        setUser(new User());
        return "consultUser.jsf";
    }

    public String removeUser() {
        User UserTemp = (User) (listUsers.getRowData());
        BaseDAO dao = new UserDAO();
        dao.remove(UserTemp);
        return "#";
    }

    public boolean getAdmin() {
        FacesContext fc = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
        User u = (User) session.getAttribute("user");
        if (u.getRole() == 1) {
            return true;
        } else {
            return false;
        }
    }

    public DataModel getListUsers() {
        List<User> list = new UserDAO().list();
        listUsers = new ListDataModel(list);
        return listUsers;
    }

    public String prepareUpdate() {
        user = (User) (listUsers.getRowData());
        return "updateUser";
    }

    public void forgotPassword() throws EmailException {
        UserDAO dao = new UserDAO();
        List<User> list = dao.consultUser(user.getEmail());
        for (User u : list) {
            user.setName(u.getName());
            user.setPassword(u.getPassword());
        }
        SendEmail se = new SendEmail();
        se.sendemailForgot(user);
        setUser(new User());
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String prepRegisterUser() {
        return "registerUser.jsf";
    }

    public String prepLogin() {
        return "login.jsf";
    }

    public String prepForgotPassword() {
        return "forgotPassword.jsf";
    }

    public void setNewUser() {
        setUser(new User());
    }
}
